home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2996 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.6 KB

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: [Q] new-allocated objects within try block
  5. Date: Sun, 21 Jan 1996 14:04:00 +0100
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <310239C0.41C67EA6@intellektik.informatik.th-darmstadt.de>
  8. References: <monnet-2001962147210001@alpnet76.alpes-net.fr>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b5 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. Nicolas Monnet wrote:
  16. > Here's the problem I'm facing -- it's probably a bad approach, it's even
  17. > possibly answered in some faq but...
  18. > I need to allocate an object with new, and delete it in the same block,
  19. > as if it was allocated on the stack.
  20. > Why? Well, I'm using an abstract base class, and I have different descendents,
  21. > and, of course, I create one of them. Example:
  22. > class ABC { public: virtual void DoSomething() = 0; };
  23. > class A : public ABC { public: virtual void DoSomething(); };
  24. > class B : public ABC { public: virtual void DoSomething(); };
  25. > (...)
  26. > try {
  27. >    ABC *p;
  28. >    if (test) {
  29. >      ..
  30. >      p = new A;
  31. >    } else {
  32. >       ...
  33. >       p = new B;
  34. >    }
  35. >    ...
  36. >    throw sthg;
  37. >    ...
  38. >    p->DoSomething();
  39. >    delete p;
  40. > } catch (...) {
  41. > }
  42. > Then, *p is not properly destroyed, isn't it?
  43. > What is another way of doing it?
  44.  
  45. Wrap the object, using a class like 'auto_ptr'.
  46. In addition your base-class 'ABC' must provide
  47. a virtual dtor.
  48.         
  49.     Enno
  50.